package netty.com.netty;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * @Title: netty的服务器端
 * @Description: netty的服务器端
 * @Author: lils
 * @CreateTime: 2018-05-17 14:16
 */
public class nettyServer {

    public static void main(String[] args) {
        // nettyServer服务启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
        // 设置一个处理客户端消息和各种消息事件的类（handler）
        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new nettyServerHandler());
            }
        });
        // 开放8000端口供客户端访问。
        serverBootstrap.bind(new InetSocketAddress(8181));
    }

    /**
     * 当有客户端绑定到服务端的时候触发，打印"Hello world, I'm server."
     */
    private static class nettyServerHandler extends SimpleChannelHandler {
        @Override
        public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
            System.out.println("Hello world, I'm nettyServer.");
        }
    }
}
